<?php
declare(strict_types=1);
namespace SixShop\AliyunIDCard;

use Symfony\Component\HttpClient\HttpClient;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use function SixShop\Core\throw_logic_exception;

class IDCardClient
{

    private const string GATEWAY = 'https://idcard.market.alicloudapi.com/';

    private HttpClientInterface $httpClient;

    private array $errorMesageMap = [
        '5' => '身份证和姓名不匹配',
        '14' => '无此身份证号码',
        '96' => '验证失败，请稍后重试',
    ];

    public function __construct(private Config $config)
    {
        $this->httpClient = HttpClient::create([
            'base_uri' => self::GATEWAY,
            'headers' => [
                'Authorization' => 'APPCODE ' . $this->config->app_code,
            ]
        ]);
    }


    public function idcard(string $cardno, string $name): array
    {
        $response = $this->httpClient->request('GET', 'lianzhuo/idcard', [
            'query' => [
                'cardno' => $cardno,
                'name' => $name,
            ]
        ]);
        $result = json_decode($response->getContent(), true);
        if ($result['resp']['code'] == 0) {
            return $result['data'];
        } else {
            throw new \RuntimeException($this->errorMesageMap[$result['resp']['code']] ?? $result['resp']['desc']);
        }
    }
}